package com.alibaba.cirtus.ots.application.app.ability.facade.v2serviceimpl;

import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.*;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.PlatformEnhanceService;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.crunifiedinventory.model.dto.GetListWarehouseStockRequest;
import com.epoch.app.crunifiedinventory.model.dto.WarehouseInventory;
import com.epoch.app.crunifiedinventory.service.CrUnifiedInventoryService;
import com.epoch.app.otsapplicationappsdk.inventoryinquirylist.dto.AsyncRequest;
import com.epoch.app.otsapplicationappsdk.inventoryinquirylist.dto.RenderRequest;
import com.epoch.app.otsapplicationappsdk.inventoryinquirylist.service.InventoryInquiryListService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class InventoryInquiryListV2ServiceImpl implements InventoryInquiryListService {

    private static Log log = Log.getLogger(InventoryInquiryListV2ServiceImpl.class);

    @Autowired
    private BaseDataService baseDataService;

    @Autowired
    private UnifiedInventoryService unifiedInventoryService;

//    @Autowired
//    private OtsUnifiedInventoryService otsUnifiedInventoryService;
    @Autowired
    private CrUnifiedInventoryService otsUnifiedInventoryService;

    @Autowired
    private PlatformEnhanceService platformEnhanceService;

    @Override
    public Object render(RenderRequest renderRequest) {
        JSONObject result = new JSONObject();
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(renderRequest.getAttr()));
        Integer pageSize = jsonObject.getInteger("pageSize");
        int limit = pageSize != null ? pageSize : 10;
        Integer currentPage = jsonObject.getInteger("currentPage");
        if (currentPage == null) {
            currentPage = 1;
        }
        int start = (currentPage - 1) * limit;
        try {
//            GetListWarehouseStockForPageRequest request = new GetListWarehouseStockForPageRequest();
            GetListWarehouseStockRequest request = new GetListWarehouseStockRequest();
            WarehouseInfo warehouseInfo = getDefaultWarehouseInfo();
            log.info("warehouseInfo:" + JSON.toJSONString(warehouseInfo));
            result.put("selectedValue", warehouseInfo.getName());
            String warehouseAreaId = warehouseInfo.getId();
            result.put("selectedId", warehouseAreaId);
            request.setWarehouseAreaId(warehouseAreaId);
            request.setType("1");
            request.setStart(start);
            request.setSize(limit);
            request.setPage(currentPage);
            request.setSearchForPage(true);
            log.info("render_otsUnifiedInventoryService.getListWarehouseStock$request:" + JSON.toJSONString(request));
            Result<List<WarehouseInventory>> response = otsUnifiedInventoryService.getListWarehouseStock(request);
//            GetListWarehouseStockForPageResponse response = otsUnifiedInventoryService.getListWarehouseStockForPage(request);
            log.info("render_otsUnifiedInventoryService.getListWarehouseStock$response:" + JSON.toJSONString(response));
            if (response==null){
                throw new Exception("未查到结果");
            }
            JSONObject page = new JSONObject();
            page.put("pageSize", limit);
            page.put("currentPage", currentPage);
            page.put("total", response.getTotal());
            int totalPage = response.getTotal() / limit;
            if (response.getTotal()%limit>0){
                totalPage++;
            }
            page.put("totalPage", totalPage);
            result.put("page", page);
            result.put("success",response.isSuccess());
            result.put("itemList",response.getResult());
            if (currentPage>1){
                result.put("reload", false);
            }
            log.info("result:" + JSON.toJSONString(result));
        }catch (Exception e){
            result.put("success", false);
            result.put("msg",e.getMessage());
        }
        return result;
    }

    @Override
    public Object async(AsyncRequest asyncRequest) {
        Object requestBody = asyncRequest.getAttr();
        if (requestBody == null) {
            return null;
        }
        JSONObject result = new JSONObject();
        try {
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(requestBody));
            JSONObject fields = jsonObject.getJSONObject("fields");
            Integer currentPage = fields.getInteger("currentPage");
            Integer pageSize = fields.getInteger("pageSize");
            int limit = 10;
            if (pageSize != null) {
                limit = pageSize;
            }
            if (currentPage == null) {
                currentPage = 1;
            }
            int start = (currentPage - 1) * limit;
//            GetListWarehouseStockForPageRequest request = new GetListWarehouseStockForPageRequest();
            GetListWarehouseStockRequest request = new GetListWarehouseStockRequest();
            JSONArray array = fields.getJSONArray("selectOptions");
            if (array!=null && array.size()>0) {
                JSONObject selected = array.getJSONObject(0).getJSONObject("selected");
                if (selected!=null) {
                    String warehouseAreaId = selected.getString("id");
                    if (StringUtils.isNotBlank(warehouseAreaId)) {
                        request.setWarehouseAreaId(warehouseAreaId);
                        result.put("selectedId", warehouseAreaId);
                    }
                }
            }
            String fuzzyName = fields.getString("value");
            if (StringUtils.isNotBlank(fuzzyName)) {
                List<String> goodIds = getGoodsIdList(fuzzyName);
                if (CollectionUtils.isEmpty(goodIds)){
                    result.put("success", true);
                    return result;
                }
                request.setGoodsIds(goodIds);
            }
            request.setType("1");
            request.setStart(start);
            request.setSize(limit);
            request.setPage(currentPage);
            request.setSearchForPage(true);
            log.info("async_otsUnifiedInventoryService.getListWarehouseStock$request:" + JSON.toJSONString(request));
            Result<List<WarehouseInventory>> response = otsUnifiedInventoryService.getListWarehouseStock(request);
//            GetListWarehouseStockForPageResponse response = otsUnifiedInventoryService.getListWarehouseStockForPage(request);
            log.info("async_otsUnifiedInventoryService.getListWarehouseStock$response:" + JSON.toJSONString(response));
            if (response == null) {
                throw new Exception("未查到结果");
            }
            result.put("success", response.isSuccess());
            result.put("itemList", response.getResult());
            JSONObject page = new JSONObject();
            page.put("pageSize", limit);
            page.put("currentPage", currentPage);
            page.put("total", response.getTotal());
            int totalPage = response.getTotal() / limit;
            if (response.getTotal()%limit>0){
                totalPage++;
            }
            page.put("totalPage", totalPage);
            result.put("page", page);
            if (currentPage>1){
                result.put("reload", false);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    //分页取所有商品
    private List<String> getGoodsIdList(String fuzzyName){
        List<String> result = new ArrayList<>();
        QueryGoodsListRequest request = new QueryGoodsListRequest();
        request.setTitle(fuzzyName);
        log.info("queryGoodsList_request" + JSON.toJSONString(request));
        Result<List<QueryGoodsListResponse>> queryGoodsListResponse = platformEnhanceService.queryGoodsList(request);
        if (!queryGoodsListResponse.isSuccess() || CollectionUtils.isEmpty(queryGoodsListResponse.getResult())){
            return result;
        }
        for (QueryGoodsListResponse response:queryGoodsListResponse.getResult()){
            JSONObject object = (JSONObject)JSON.toJSON(response);
            JSONArray jsonArray = object.getJSONArray("goodsList");
            if (jsonArray.isEmpty()){
                continue;
            }
            for (Object o : jsonArray){
                JSONObject good = (JSONObject)JSON.toJSON(o);
                result.add(good.getString("id"));
            }
        }
        return result;
    }

    //默认取用户权限下一个逻辑仓
    private WarehouseInfo getDefaultWarehouseInfo() throws Exception{
        SearchWarehouseForPullRequest input = new SearchWarehouseForPullRequest();
        input.setModel(3);
        log.info("unifiedInventoryService.wmsQueryWarehouseZoneList$request:" + JSON.toJSONString(input));
        SearchWarehouseForPullResponse response = unifiedInventoryService.searchWarehouseForPull(input);
        log.info("unifiedInventoryService.wmsQueryWarehouseZoneList$response:" + JSON.toJSONString(response));
        if (response == null || CollectionUtils.isEmpty(response.getResult())) {
            throw new Exception("未查到当前用户组织权限下的逻辑仓库");
        }
        return response.getResult().get(0);
    }
}
